﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using AutoLoL.Entities;
using AutoLoL.Logic.Parsers;
using System.Collections.ObjectModel;

namespace AutoLoL.Playground
{
    /// <summary>
    /// Interaction logic for ForumWindow.xaml
    /// </summary>
    public partial class ForumWindow : Window
    {
        public ForumWindow()
        {
            InitializeComponent();

            const string baseDirectory = "Forum";
            const string imagesDirectory = "champions";

            if (!Directory.Exists(baseDirectory))
            {
                Directory.CreateDirectory(baseDirectory);
            }

            if (!Directory.Exists(Path.Combine(baseDirectory, imagesDirectory)))
            {
                Directory.CreateDirectory(Path.Combine(baseDirectory, imagesDirectory));
            }

            Dictionary<string, string> championLines = new Dictionary<string, string>();

            Func<string, bool> filter = ((path) =>
                path.ToLower().StartsWith("data/characters")
                && path.ToLower().EndsWith(".inibin")
                && path.Split('/').Length == 4);

            ReadOnlyCollection<RafFile> rafFiles = RafManager.Instance.GetFiles(filter);

            foreach (RafFile rafFile in rafFiles)
            {
                if (rafFile.Data == null)
                {
                    RafManager.Instance.SetRafFileData(rafFile);
                }

                Dictionary<uint, InibinEntry> data = InibinParser.ParseBytes(rafFile.Data);

                if (data.ContainsKey((uint)InibinKeys.Character.IS_CHAMPION) && data[(uint)InibinKeys.Character.IS_CHAMPION].GetString().ToLower().Equals("true"))
                {
                    string directoryName = rafFile.PathChunks[rafFile.PathChunks.Length - 2];

                    // Parse FC
                    string fckName = data[(uint)InibinKeys.Character.FCK_NAME].GetString();
                    string fckDescription = data[(uint)InibinKeys.Character.FCK_DESCRIPTION].GetString();

                    string name = FontConfigParser.Instance.GetValue(fckName);
                    string description = FontConfigParser.Instance.GetValue(fckDescription);

                    string iconFilename = data[(uint)InibinKeys.Character.PATH_ICON_DDS].GetString();
                    string iconPath = string.Format("data/characters/{0}/info/{1}", directoryName, iconFilename);
                    RafFile iconRafFile = RafManager.Instance.GetFile(iconPath);
                    RafManager.Instance.SetRafFileData(iconRafFile);

                    BitmapSource iconBitmap = null;
                    if (iconFilename.ToLower().EndsWith(".dds"))
                    {
                        iconBitmap = ImageParser.DdsToBitmapSource(iconRafFile.Data);
                    }
                    else if (iconFilename.ToLower().EndsWith(".tga"))
                    {
                        iconBitmap = ImageParser.TgaToBitmapSource(iconRafFile.Data);
                    }

                    string imageName = string.Format("{0}.jpg", name);
                    string imagePath = Path.Combine(baseDirectory, imagesDirectory, imageName);
                    using (FileStream stream = new FileStream(imagePath, FileMode.Create))
                    {
                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(iconBitmap));
                        encoder.Save(stream);
                    }

                    string wiki = string.Format("http://leagueoflegends.wikia.com/wiki/{0}", name);
                    string tooltip = string.Format("{0}, {1}", name, description);
                    string image = string.Format("http://codingquirks.com/apps/autolol/images/{0}/{1}", imagesDirectory, imageName);

                    // Create the forum line and store in a dictionary for sorting
                    string line = string.Format("[url=\"{0}\"][img=50,50,0,left,\"{1}\"]{2}[/img][/url]", wiki, tooltip, image);
                    championLines.Add(name, line);
                }
            }

            string result = string.Format("There are {0} champions.", championLines.Count);
            result += Environment.NewLine;
            result += "[table][tr][td]";
            result += Environment.NewLine;

            // Sort and write
            foreach (string line in championLines.OrderBy(c => c.Key).Select(c => c.Value))
            {
                result += line;
            }

            result += Environment.NewLine;
            result += "[/td][/tr][/table]";

            textBox1.Text = result;
        }
    }
}
